package service

import (
	"admin-system-go/model"
	"admin-system-go/model/do"
	"admin-system-go/model/dto"
	"admin-system-go/repository"
)

type RoleService interface {
	QueryRole(dto dto.RoleQueryDTO) model.ResponseEntity
	CreateRole(dto dto.RoleBaseDTO) model.ResponseEntity
	DelRole(dto dto.RoleDelDTO) model.ResponseEntity
	UpdateRole(updateDTO dto.RoleUpdateDTO) model.ResponseEntity
}

type roleServiceImpl struct{}

func (roleService roleServiceImpl) QueryRole(queryDto dto.RoleQueryDTO) model.ResponseEntity {
	var role do.Role
	_ = repository.Copy(queryDto, &role)
	var roles []do.Role
	pageSize := queryDto.PageSize
	pageNo := queryDto.PageNo
	var total int64
	_ = repository.GetDb().Where(&role).Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&roles)
	var result = make([]dto.RoleQueryDTO, len(roles))
	if len(roles) != 0 {
		_ = repository.GetDb().Model(&do.Role{}).Where(&role).Count(&total)
	}
	_ = repository.CopySlice(roles, result)
	return model.PageEntityModel(result, &model.PageInfo{
		Total:    total,
		PageSize: pageSize,
		PageNo:   pageNo,
	})
}

func (roleService roleServiceImpl) CreateRole(createDto dto.RoleBaseDTO) model.ResponseEntity {
	var role do.Role
	_ = repository.Copy(createDto, &role)
	tx := repository.GetDb().Where(&do.Role{Name: createDto.Name}).Find(&role)
	if tx.RowsAffected > 0 {
		return model.FailEntityModel("角色已经存在")
	}
	tx = repository.GetDb().Create(&role)
	return model.BoolEntityModel(tx.RowsAffected == 1, tx.Error)
}

func (roleService roleServiceImpl) DelRole(delDto dto.RoleDelDTO) model.ResponseEntity {
	tx := repository.GetDb().Delete(&do.Role{}, delDto.RoleIds)
	return model.BoolEntityModel(tx.RowsAffected >= 1, tx.Error)
}

func (roleService roleServiceImpl) UpdateRole(updateDTO dto.RoleUpdateDTO) model.ResponseEntity {
	var oldRole do.Role = do.Role{Model: model.Model{Id: updateDTO.Id}}
	tx := repository.GetDb().Model(&oldRole).Find(&oldRole)
	if tx.RowsAffected == 0 {
		return model.FailEntityModel("角色不存在")
	}
	_ = repository.Copy(updateDTO, &oldRole)
	tx = repository.GetDb().Model(&oldRole).Save(&oldRole)
	if tx.Error == nil {
		return model.SuccessEntityModel(true)
	} else {
		return model.FailEntityModel("更新失败")
	}
}
